package com.lmk.ms.common.net.udp.server.service.impl;

import com.lmk.ms.common.net.udp.server.service.UdpServerService;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * UDP服务端业务服务适配器
 * @author laomake@hotmail.com
 * @version 1.0
 * @date 2023/4/25
 */
@Slf4j
public abstract class UdpServerServiceAdapter implements UdpServerService {

    @Override
    public void handel(DatagramSocket socket, DatagramPacket packet) {
        if(packet == null){
            log.error("业务处理失败，packet不可为空！");
            return;
        }

        DatagramPacket reply = service(packet);
        if(reply != null){
            try {
                socket.send(reply);
            } catch (IOException e) {
                log.error("回复客户端失败：", e);
            }
        }
    }

    /**
     * 处理数据包，子类在重写此方法时，不要处理IO异常
     * @param packet
     * @return  返回值不为空，则会自动回复
     */
    public abstract DatagramPacket service(DatagramPacket packet);


}
